<template>
  <div class="app-container">
    <div class="app-box">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="板块名称" prop="name">
          <el-input maxlength="50"
                    v-model="queryParams.name"
                    placeholder="请输入板块名称"
                    clearable
                    @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['biz:bizSector:add']"
          >新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="info" plain icon="Upload" @click="handleImport" v-hasPermi="['biz:bizSector:import']">导入
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['biz:bizSector:export']"
          >导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
              type="info"
              plain
              icon="Sort"
              @click="toggleExpandAll"
          >展开/折叠
          </el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-tree
          v-loading="loading"
          v-if="refreshTable"
          :data="bizSectorList"
          :props="{label: 'name'}"
          node-key="id"
          @node-click="nodeClick"
          :default-expand-all="isExpandAll"
          :expand-on-click-node="false"
      >
        <template #default="{ node, data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span>
            <el-tooltip content="编辑" placement="top">
              <el-button link type="primary"
                         v-hasPermi="['biz:bizSector:edit']"
                         icon="Edit"
                         @click="() => handleUpdate(data)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="添加子级" placement="top">
            <el-button link type="primary"
                       v-hasPermi="['biz:bizSector:add']"
                       icon="Plus" @click="() => handleAdd(data)">
            </el-button>
              </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary"
                         v-hasPermi="['biz:bizSector:remove']"
                         icon="Delete" @click="() => handleDelete(data)">
              </el-button>
            </el-tooltip>
            <el-tooltip content="项目字段配置" placement="top" :disabled="data.children && data.children.length > 0">
              <el-button :disabled="data.children && data.children.length > 0"
                         link type="primary"
                         v-hasPermi="['biz:bizSector:edit']"
                         icon="List"
                         @click="() => nodeClick(data)">
              </el-button>
            </el-tooltip>
          </span>
        </span>
        </template>
      </el-tree>

      <!-- 添加或修改项目板块管理对话框 -->
      <el-dialog :close-on-click-modal="false" draggable :title="title" v-model="open" width="500px" append-to-body @close="cancel">
        <el-form ref="bizSectorRef" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="板块名称" prop="name">
            <el-input maxlength="50" v-model="form.name" placeholder="请输入板块名称"/>
          </el-form-item>
          <el-form-item label="板块代号" prop="code">
            <el-input maxlength="50" v-model="form.code" placeholder="请输入板块代号"/>
          </el-form-item>
          <el-form-item label="父级" prop="parentId">
            <el-tree-select
                v-model="form.parentId"
                :data="bizSectorOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="请选择父级"
                check-strictly
            />
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNum">
            <el-input maxlength="50" v-model="form.orderNum" placeholder="请输入显示顺序"/>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
      <!-- 导入对话框 -->
      <el-dialog :close-on-click-modal="false" draggable :title="upload.title" v-model="upload.open" width="400px" append-to-body>
        <el-upload ref="uploadRef" :limit="1" accept=".xlsx, .xls" :headers="upload.headers"
                   :action="upload.url"
                   :disabled="upload.isUploading"
                   :before-upload="handleFileChange"
                   :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <el-icon class="el-icon--upload">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <template #tip>
            <div class="el-upload__tip text-center">
              <span>仅允许导入xls、xlsx格式文件。</span>
              <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline"
                       @click="importTemplate">下载模板
              </el-link>
            </div>
          </template>
        </el-upload>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitFileForm">确 定</el-button>
            <el-button @click="upload.open = false">取 消</el-button>
          </div>
        </template>
        <div v-html="importResult" style="color: red"></div>
      </el-dialog>
    </div>
    <div v-if="selectId>0" class="app-box app-box-margin">
      <el-text class="mx-1" size="large">
        <el-text class="mx-1" size="large" type="success">{{ rightTitle }}</el-text>
        录入字段配置
      </el-text>
      <div class="el-table--fit el-table--scrollable-y el-table--enable-row-hover el-table--enable-row-transition el-table--default
           el-table el-table--layout-fixed"
           data-prefix="el" style="width: 100%; margin-top: 20px; height: calc(100% - 42px);overflow: auto">
        <div class="el-table__header-wrapper">
          <table class="el-table__header" border="0" cellpadding="0" cellspacing="0" style="width: 100%;">

            <thead class="">
            <tr class="">
              <th class="el-table_2_column_5 is-leaf el-table__cell" colspan="1" rowspan="1">
                <div class="cell" style="padding-left: 50px">字段</div>
              </th>
              <th class="el-table_2_column_6 is-leaf el-table__cell" colspan="1" rowspan="1">
                <div class="cell">显示</div>
              </th>
              <th class="el-table_2_column_7 is-leaf el-table__cell" colspan="1" rowspan="1">
                <div class="cell">必填</div>
              </th>
            </tr>
            </thead>
          </table>
        </div>
        <div class="el-table__body-wrapper">
          <div class="el-scrollbar">
            <div class="el-scrollbar__wrap el-scrollbar__wrap--hidden-default" style="height: 100%;">
              <div class="el-scrollbar__view" style="display: inline-block; vertical-align: middle;width: 100%;">

                <el-collapse v-model="activeNames" style="width: 100%;">
                  <el-collapse-item v-for="parent of fieldList" :key="parent" :title="parent.name" :name="parent.code" style="width: 100%;">
                    <table class="el-table__body" cellspacing="0" cellpadding="0" border="0"
                           style="table-layout: fixed; width: 100%;box-sizing: border-box">

                      <tbody tabindex="-1">
                      <tr class="el-table__row" v-for="item of parent.children" :key="item">
                        <td class="el-table_1_column_1 el-table__cell" rowspan="1" colspan="1">
                          <div class="cell" style="padding-left: 50px">{{ item.name }}</div>
                        </td>
                        <td class="el-table_1_column_2 el-table__cell" rowspan="1" colspan="1">
                          <div class="cell">
                            <el-switch v-model="item.show" @change="changeField"/>
                          </div>
                        </td>
                        <td class="el-table_1_column_3 el-table__cell" rowspan="1" colspan="1">
                          <div class="cell">
                            <el-switch v-if="item.show" v-model="item.required" @change="changeField"/>
                          </div>
                        </td>
                      </tr>
                      </tbody>
                    </table>
                  </el-collapse-item>
                </el-collapse>
              </div>
            </div>
            <div class="el-scrollbar__bar is-horizontal" style="display: none;">
              <div class="el-scrollbar__thumb" style="transform: translateX(0%);"></div>
            </div>
            <div class="el-scrollbar__bar is-vertical" style="display: none;">
              <div class="el-scrollbar__thumb" style="transform: translateY(0%); height: 252.518px;"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup name="BizSector">
import {
  listBizSector, getBizSector, delBizSector, addBizSector,
  updateBizSector, getConfigAll, saveConfigAll
} from "@/api/biz/bizSector";
import {currentDate} from '@/utils/dateutil';
import {getToken} from "@/utils/auth";

const {proxy} = getCurrentInstance();

const fieldList = ref([]);
const bizSectorList = ref([]);
const bizSectorOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);
const selectId = ref(0);
const rightTitle = ref("");
const activeNames = ref(["t1", "t2", "t3", "t4", "t5", "t6", "t7"]);
const importResult = ref("");
/*** 导入参数 */
const upload = reactive({
  // 是否显示弹出层（导入）
  open: false,
  // 弹出层标题（导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "/biz/bizSector/importExcel"
});
const data = reactive({
  form: {},
  queryParams: {
    name: null,
    code: null,
    parentId: null,
  },
  rules: {
    parentId: [
      {required: true, message: "上级不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "板块名称不能为空", trigger: "blur"}
    ],
    code: [
      {required: true, message: "板块代号不能为空", trigger: "blur"}
    ],
    orderNum: [
      {required: true, message: "显示排序不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules} = toRefs(data);

function changeField() {
  console.log(fieldList.value);
  let obj = {};
  obj.id = selectId.value;
  obj.data = fieldList.value;
  saveConfigAll(obj).then(response => {

  }).catch(error => {
    configAll();
  });
}

function nodeClick(el, node, t, event) {
  if (!(el.children && el.children.length > 0)) {
    selectId.value = el.id;
    rightTitle.value = el.name;
    configAll();
  } else {
    fieldList.value = [];
    selectId.value = 0;
    rightTitle.value = '';
  }
}

function configAll() {
  loading.value = true;
  getConfigAll(selectId.value).then(response => {
    fieldList.value = response.data;
    loading.value = false;
  });
}

/** 查询项目板块管理列表 */
function getList() {
  loading.value = true;
  listBizSector(queryParams.value).then(response => {
    bizSectorList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}

/** 查询项目板块管理下拉树结构 */
function getTreeselect() {
  listBizSector().then(response => {
    bizSectorOptions.value = [];
    const data = {id: 0, name: '顶级节点', children: []};
    data.children = proxy.handleTree(response.data, "id", "parentId");
    bizSectorOptions.value.push(data);
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    createTime: null,
    updateTime: null,
    deleted: null,
    ancestors: null,
    name: null,
    code: null,
    parentId: null,
    orderNum: null
  };
  proxy.resetForm("bizSectorRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加项目板块管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  getBizSector(row.id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目板块管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["bizSectorRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateBizSector(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addBizSector(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除项目板块数据项？').then(function () {
    return delBizSector(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导入按钮操作 */
function handleImport() {
  upload.title = "项目板块导入";
  upload.open = true;
}

/** 下载模板操作 */
function importTemplate() {
  proxy.download('biz/bizSector/download', {}, `项目板块模板-${currentDate()}.xlsx`)
}

/** 提交上传文件 */
function submitFileForm() {
  console.log(proxy.$refs["uploadRef"])
  proxy.$refs["uploadRef"].submit();
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  console.log('handleFileUploadProgress')
  upload.isUploading = true;
};

const handleFileChange = (event, file, fileList) => {
  importResult.value="";
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  if (response.code == 200) {
    upload.open = false;
    proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    getList();
  } else {
    importResult.value = response.msg;
  }
};
/** 导出按钮操作 */
function handleExport() {
  proxy.download('biz/bizSector/export', {
    ...queryParams.value
  }, `项目板块-${currentDate()}.xlsx`)
}
getList();
</script>
<style scoped>
.app-container {
  height: calc(100vh - 84px);
  background-color: #f6f6f6;
  padding: 10px;
}

.app-box {
  width: calc(50% - 5px);
  height: 100%;
  background-color: #ffffff;
  padding: 20px;
  border-radius: 6px;
  float: left;
}

.app-box-margin {
  margin-left: 10px;
  overflow-y: auto;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
::v-deep .el-collapse-item__content{
  padding: 0!important;
}
::v-deep .el-tree {
  height: calc(100% - 82px);
  overflow: auto;
}
</style>
